package cn.st4rlight.util.id;

import java.util.Random;
import java.util.UUID;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * id相关工具类
 *
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-05-20
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IDUtil {

    private static final Random RANDOM = new Random(System.currentTimeMillis());


    /**
     * 随机生成12位的唯一整数，对于百万因为数据完全足够
     * 若后续数据量增大，可以考虑换成13位随机数，或者15位、18位雪花
     */
    public static long getUUID12() {
        long uuid12 = IDUtil.doGenUUID(12);
        while (uuid12 == 0) {
            uuid12 = IDUtil.doGenUUID(12);
        }
        return uuid12;
    }

    /**
     * 生成UUID不带-
     */
    public static String getUUIDNoDash() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 随机生成n位的唯一整数
     * 冲突的概率为 1 / (10 ^ numCnt)
     * 当n >= 12, 对于数据在百万级以内的可以忽略id冲突的问题
     */
    private static long doGenUUID(int numCnt) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < numCnt; i++) {
            builder.append(RANDOM.nextInt(10));
        }
        // 开头的0跟后面第一个不是0的数字换一下位置
        if (builder.charAt(0) == '0') {
            for (int i = 1; i < builder.length(); i++) {
                if (builder.charAt(i) != '0') {
                    builder.setCharAt(0, builder.charAt(i));
                    builder.setCharAt(i, '0');
                    break;
                }
            }
        }
        return Long.parseLong(builder.toString());
    }
}
